package com.young.filesystem.model;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.Base64Utils;

/**
 * 文件签名防伪
 */
@Getter
@Setter
@Builder
public class FileClaims implements Serializable {

    // 机构
    private String         o;
    @JSONField(ordinal = 2)
    // 加密方式
    private String         e;
    @JSONField(ordinal = 3)
    // 载体
    private String         p;
    // 到期时间
    @JSONField(ordinal = 1)
    private   long         x;
    // 签名
    @JSONField(serialize = false)
    private String         s;

    public FileClaims selfSignature() {
        StringBuilder sb = new StringBuilder();
        this.s = sb.append((char) ('a' + (int) (Math.random() * 26))).append((char) ('a' + (int) (Math.random() * 26))).toString();
        return this;
    }

    @Override
    public String toString() {
        return Base64Utils.encodeToUrlSafeString(JSON.toJSONBytes(this)) + s;
    }

    public static void main(String[] args) throws Exception {
        String a = FileClaims.builder().o("ZGX").e("B64").x(System.currentTimeMillis()).p("1").build().selfSignature().toString();
        System.out.println(a);
        System.out.println(new String(Base64Utils.decodeUrlSafe(a.substring(0, a.length() - 2).getBytes(StandardCharsets.UTF_8))));
    }

}
